package com.edgardeng.generator.controller;

import com.edgardeng.generator.entity.SQLDataSource;
import com.edgardeng.generator.entity.Module;
import com.edgardeng.generator.service.DataProviderService;
import com.edgardeng.generator.service.FileGeneratorService;
import com.edgardeng.generator.service.SysGeneratorService;
import com.edgardeng.utils.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 代码生成器
 *
 * @author edgardeng (https://edgardeng.github.io)
 */
@RestController
@RequestMapping("/api/generator")
public class GeneratorController {
    @Autowired
    private SysGeneratorService sysGeneratorService;
    @Autowired
    private FileGeneratorService fileGeneratorService;

    /**
     * 获取某个数据源的 Table List
     */
    @RequestMapping(value = "/table")
    @ResponseBody
    public List tableList(@Validated SQLDataSource model) {
        checkDataSource(model);
        return sysGeneratorService.queryTables(model);
    }

    /** 查询数据库的表 */
//    @ResponseBody
//    @RequestMapping("/list")
//    public PageUtils list(@RequestParam Map<String, Object> params, HttpServletResponse response) {
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//        response.setHeader("Access-Control-Max-Age", "3600");
//        response.addHeader("Access-Control-Allow-Headers", "*");
//        //查询列表数据
//        Query query = new Query(params);
//        List<Map<String, Object>> list = sysGeneratorService.queryList(query);
//        int total = sysGeneratorService.queryTotal(query);
//        PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());
//        return pageUtil;
//    }

    /** 生成代码 */
//    @RequestMapping("/code2")
//    public void code(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        String[] tableNames = new String[]{};
//        String tables = request.getParameter("tables");
//        tableNames = tables.split(",");
//
//        byte[] data = sysGeneratorService.generatorCode(tableNames);
//
//        response.reset();
//        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
//        response.addHeader("Content-Length", "" + data.length);
//        response.setContentType("application/octet-stream; charset=UTF-8");
//        IOUtils.write(data, response.getOutputStream());
//    }

    /** 通过数据库生成代码*/
    @RequestMapping("/code")
    public String code(@Validated SQLDataSource model, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(model.getTables())) {
            throw new RuntimeException("table 为空");
        }
        checkDataSource(model);
        byte[] data = sysGeneratorService.generatorCode(model);
        return "success to build code ";
//        response.reset();
//        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
//        response.addHeader("Content-Length", "" + data.length);
//        response.setContentType("application/octet-stream; charset=UTF-8");
//        IOUtils.write(data, response.getOutputStream());
    }

    /** 生成模块代码 */
    @RequestMapping("/module")
    public String module(@Validated Module module){
        checkModuleParameter(module);
        fileGeneratorService.generateModule(module);
        return "success to build module <" + module.getName() + ">";
    }

    /**
     * 生成一个jupiter项目
     * 含多个模块: auth
     */
    @RequestMapping("/project")
    public String project(@Validated Module project) {
        checkModuleParameter(project);
        fileGeneratorService.generateProject(project);
        return "success to build project <" + project.getName() + ">";
    }

    private void checkModuleParameter(Module m) {
        if (StringUtils.isBlank(m.getDir())) {
            throw new RuntimeException("dir 为空");
        }
        if (StringUtils.isBlank(m.getName())) {
            throw new RuntimeException("name 为空");
        }
        if (StringUtils.isBlank(m.getDesc())) {
            throw new RuntimeException("desc 为空");
        }
        if (StringUtils.isBlank(m.getPackageName())) {
            throw new RuntimeException("packageName 为空");
        }
    }

    private void checkDataSource(SQLDataSource m) {
        if (StringUtils.isBlank(m.getName())) {
            throw new RuntimeException("数据库名name 为空");
        }
        if (StringUtils.isBlank(m.getHost())) {
            throw new RuntimeException("host 为空");
        }
        if (StringUtils.isBlank(m.getUsername())) {
            throw new RuntimeException("getUsername 为空");
        }
        if (StringUtils.isBlank(m.getPassword())) {
            throw new RuntimeException("getPassword 为空");
        }
    }


    /**
     * 生成数据表文档
     */
    @RequestMapping("/db_docs")
    public void module(HttpServletResponse response) throws IOException {
        // todo 暂时无法 指定数据库，只能使用 application.yaml 中配置的数据库

        byte[] data = sysGeneratorService.generatorDBDocument();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
